﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using SpicIE.Common;
using System.Windows.Forms;
using IEAccessibleTabs;
using System.IO;
using SHDocVw;


namespace TabSaver.LoadTabsFrom
{
    /// <summary>
    /// This is a simple COM object wich implements the IOleCommandTarget.
    /// The interface is needed when a COM object shall be called via COM object invoke by another component.
    /// There are two needed interface member implementations which can be changed to match the demands of the user
    /// when the plugin is called.
    /// </summary>
    [ComVisible(true),
    ClassInterface(ClassInterfaceType.AutoDual),
    Guid(LoadTabsFromObject.PLUGIN_GUID),
    ProgId(LoadTabsFromObject.PLUGIN_PROGID)]
    public class LoadTabsFromObject : IOleCommandTarget
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();


        public const string PLUGIN_GUID = "C2A19974-B7CB-47a3-ACA2-2651A0967DF3";
        public const string PLUGIN_PROGID = "TabSaver.LoadTabsFromObject";

        public LoadTabsFromObject()
        {
            // nothing needs to be done here, since this plugin shall only do 
            //something when invoked by another COM object via IOleCommandTarget::Exec
        }

        #region IOLECommandTarget interface implementation
        /// <summary>
        /// interface implementation for communicating with the ole object, in this case the menuitem as com object
        /// </summary>
        /// <param name="pguidCmdGroup"></param>
        /// <param name="cCmds"></param>
        /// <param name="prgCmds"></param>
        /// <param name="pCmdText"></param>
        /// <returns>-1</returns>
        public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
        {
            return -1;
        }

        /// <summary>
        /// interface implementation for firing the OLE Command event which can be subscribed in the intatiated class
        /// </summary>
        /// <param name="pguidCmdGroup"></param>
        /// <param name="nCmdID"></param>
        /// <param name="nCmdexecopt"></param>
        /// <param name="pvaIn"></param>
        /// <param name="pvaOut"></param>
        /// <returns>-1</returns>
        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            StreamReader re = null;
            try
            {
                IEAccessible IEAccessor = new IEAccessible();

                OpenFileDialog Loader = new OpenFileDialog();
                Loader.Filter = "Tab Files (*.tab)|*.TAB";

                if (Directory.Exists(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + Path.DirectorySeparatorChar + "IETabs"))
                {
                    Loader.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + Path.DirectorySeparatorChar + "IETabs";
                }
                else
                {

                }

                DialogResult Result = Loader.ShowDialog();
                if (Result == DialogResult.OK)
                {
                    re = new StreamReader(Loader.FileName);
                    string input;
                    object navOpenInNewTab = 0x0800;
                    object p = null;
                    object url = "about:blank";

                    System.Collections.IEnumerator windows = new SHDocVw.ShellWindowsClass().GetEnumerator();
                    while (windows.MoveNext())
                    {
                        IWebBrowser2 WebBrowserWindow = (IWebBrowser2)windows.Current;
                        try
                        {
                            if (WebBrowserWindow.HWND == GetForegroundWindow().ToInt32())
                            {
                                while ((input = re.ReadLine()) != null)
                                {
                                    url = input;
                                    WebBrowserWindow.Navigate2(ref url, ref navOpenInNewTab, ref p, ref p, ref p);
                                }
                                break;
                            }
                        }
                        catch
                        {
                        }
                    }
                }
                else
                {
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
            finally
            {
                if (re != null)
                {
                    re.Close();
                }
            }

            return -1;
        }
        #endregion
    }
}